<!-- eslint-disable vue/valid-v-for -->
<template>
  <div>
    <div class="filter-container mt-15">
      <el-select v-model="listQuery.serverId" class="filter-item" filterable clearable placeholder="选择区服">
        <el-option v-for="item in serverList" :key="item.sid" :label="item.name + '(' + item.sid + ')'" :value="item.sid"></el-option>
      </el-select>
      <el-button class="filter-item" type="success" @click="selectTypeClick">日志类型({{ selectType }})</el-button>
      <el-input v-model="listQuery.actor" class="filter-item" style="width: 150px;" placeholder="角色ID/角色名" />
      <!-- <el-input v-model="listQuery.reason" class="filter-item" style="width: 150px;" placeholder="原因" /> -->
      <el-select v-model="listQuery.reason" class="filter-item" filterable clearable placeholder="原因">
        <el-option v-for="item in reasonList" :key="item.id" :label="item.name + '(' + item.id + ')'" :value="item.id"></el-option>
      </el-select>
      <el-select v-model="listQuery.data" class="filter-item" style="width: 120px;" clearable filterable placeholder="数据字段">
        <el-option v-for="item in data_list" :key="item.name" :label="item.label" :value="item.name"></el-option>
      </el-select>
      <el-input v-model="listQuery.dataValue" class="filter-item" style="width: 150px;" placeholder="数据字段值" />
      <el-date-picker v-model="listQuery.datetime[0]" class="filter-item" type="date" placeholder="开始日期"></el-date-picker>
      <el-date-picker v-model="listQuery.datetime[1]" class="filter-item" type="date" placeholder="结束日期"></el-date-picker>
      <el-button class="filter-item" type="primary" plain icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button :loading="downloadLoading" type="primary" icon="el-icon-download" class="filter-item" @click="handleDownload()">导出</el-button>
    </div>
    <div class="filter-container" style="margin-bottom: 10px;">
      <el-checkbox-group v-model="checkboxVal">
        <el-checkbox label="account_id">账号</el-checkbox>
        <el-checkbox label="energy_speed">赚速</el-checkbox>
        <el-checkbox label="player_power">战力</el-checkbox>
        <el-checkbox label="diamond">钻石</el-checkbox>
        <el-checkbox label="recharge_value">充值</el-checkbox>
        <el-checkbox label="real_recharge_value">真实充值金额</el-checkbox>
        <el-checkbox label="week_recharge">每周充值</el-checkbox>
        <el-checkbox label="mouth_recharge">每月充值</el-checkbox>
        <el-checkbox label="login_days">累计登录天数</el-checkbox>
      </el-checkbox-group>
    </div>
    <el-table ref="table" :key="key" v-loading="listLoading" :data="list" border stripe fit highlight-current-row class="table-content" height="650">
      <el-table-column v-for="fruit in formThead" :key="fruit" :label="fruitZh[fruit]" :align="alignHead[fruit]" :width="widthHead[fruit]">
        <template slot-scope="scope">
          {{ scope.row[fruit] }}
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    <el-dialog :visible.sync="dialogVisible" title="选择日志类型" :close-on-click-modal="false">
      <div class="server-box">
        <ul class="menu-sub">
          <li v-for="(sgit, index) in configList" :key="index">
            <el-checkbox v-model="sgit.flag" :indeterminate="itemIndeterminate(sgit)" @change="(val) => handleCheckAll(val, sgit)">{{ sgit.cname }}({{ sgit.cid }})</el-checkbox>
            <el-checkbox-group v-model="selectedData" style="padding-left: 30px;" @change="handleChanges(sgit)">
              <el-checkbox v-for="sgits in sgit.children" :key="sgits.id" :label="sgits.id">{{ sgits.name }}({{ sgits.id
              }})</el-checkbox>
            </el-checkbox-group>
          </li>
        </ul>
      </div>
      <div class="tr">
        <el-button type="primary" @click="confirmSubmit()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
const data_x = 10
const data_list = []
for (let i = 1; i <= data_x; i++) {
  data_list.push({ label: '数据' + i, name: 'data_' + i })
}
import waves from '@/directive/waves' // 实现点击波浪纹
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { getBehaviorLog, getBehaviorConfigGroup, getReasonlConfig } from '@/api/actorInfo'
import { getServerList } from '@/api/ops'
const defaultFormThead = ['server_id', 'player_id', 'player_name', 'player_level', 'player_vip', 'log_time', 'log_type', 'reason', 'data_1']
const default_pages = {
  page: 1,
  limit: 200
}
export default {
  name: 'BehaviorLog',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      key: 1,
      formTheadOptions: ['server_id', 'account_id', 'player_id', 'player_name', 'player_level', 'player_vip', 'energy_speed', 'player_power', 'diamond', 'recharge_value', 'real_recharge_value', 'week_recharge', 'mouth_recharge', 'login_days', 'log_time', 'log_type', 'reason', 'data_1'],
      checkboxVal: defaultFormThead,
      formThead: defaultFormThead,
      fruitZh: { // 中文表头映射
        server_id: '服务器',
        account_id: '账号',
        player_id: '角色ID',
        player_name: '角色名',
        player_level: '等级',
        player_vip: 'VIP',
        energy_speed: '赚速',
        player_power: '战力',
        diamond: '钻石',
        recharge_value: '充值',
        real_recharge_value: '真实充值金额',
        week_recharge: '每周充值',
        mouth_recharge: '每月充值',
        login_days: '累计登录天数',
        log_time: '日志时间',
        log_type: '日志类型',
        reason: '日志原因',
        data_1: '数据'
      },
      widthHead: { // 中文表头映射
        server_id: '80',
        account_id: '210',
        player_id: '110',
        player_name: '100',
        player_level: '50',
        player_vip: '50',
        energy_speed: '100',
        player_power: '100',
        diamond: '100',
        recharge_value: '100',
        log_time: '160',
        log_type: '80',
        reason: '120',
        data_1: '900'
      },
      alignHead: {
        server_id: 'center',
        account_id: 'center',
        player_id: 'center',
        player_name: 'center',
        player_level: 'center',
        player_vip: 'center',
        energy_speed: 'center',
        player_power: 'center',
        diamond: 'center',
        recharge_value: 'center',
        log_time: 'center',
        log_type: 'center',
        reason: 'center',
        data_1: 'left'
      },
      list: [],
      total: 0,
      serverList: [],
      data_list: data_list,
      configList: [],
      reasonList: [],
      selectedData: [],
      listLoading: false,
      downloadLoading: false,
      dialogVisible: false,
      selectType: '全部',
      listQuery: {
        page: default_pages.page,
        limit: default_pages.limit,
        serverId: '',
        type: [],
        actor: '',
        reason: '',
        data: '',
        dataValue: '',
        datetime: [new Date(), new Date()]
      }
    }
  },
  watch: {
    checkboxVal(valArr) {
      this.formThead = this.formTheadOptions.filter(i => valArr.indexOf(i) >= 0)
      this.key = this.key + 1
    }
  },
  created() {
    this.getServerList()
    this.getConfigList()
    this.getReasonlConfig()
    const id = parseInt(this.$route.params.id)
    const type = parseInt(this.$route.params.type)
    const sid = parseInt(this.$route.params.sid)
    const num = parseInt(this.$route.params.num)
    if (Number.isFinite(id) && Number.isFinite(type) && Number.isFinite(sid) && Number.isFinite(num)) {
      this.listQuery.actor = id
      this.listQuery.serverId = sid
      this.listQuery.type = type
      this.listQuery.data = 'data_1'
      this.listQuery.dataValue = num
    }
    this.init()
  },
  methods: {
    init() {
      this.getList()
    },
    async getList(param) {
      this.listQuery.type = this.selectedData
      let query = null
      if (param) {
        this.listQuery = Object.assign(this.listQuery, param)
        console.log(this.listQuery)
      }
      query = this.listQuery
      this.listLoading = true
      const res = await getBehaviorLog(query)
      this.listLoading = false
      this.list = res.data.items
      this.total = res.data.total
      this.$nextTick(() => {
        this.$refs.table.doLayout()
      })
    },
    async getReasonlConfig() {
      this.listLoading = true
      const res = await getReasonlConfig({ type: 'all' })
      this.listLoading = false
      this.reasonList = res.data.items
    },
    async getServerList(params) {
      const query = params
      const res = await getServerList(query)
      this.serverList = res.data.items
      this.loading = false
    },
    async getConfigList(params) {
      const query = params
      const res = await getBehaviorConfigGroup(query)
      this.configList = res.data
      this.loading = false
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const filterVal = []
        const tHeader = []
        for (const prop in this.fruitZh) {
          // if (this.checkboxVal.includes(prop)) {
          // eslint-disable-next-line no-constant-condition
          if (true) {
            if (prop === 'data_1') {
              for (let i = 1; i < data_x; i++) {
                tHeader.push('数据' + i)
                filterVal.push('data_' + i)
              }
            } else {
              tHeader.push(this.fruitZh[prop])
              filterVal.push(prop)
            }
          }
        }
        // console.log(filterVal)
        getBehaviorLog(Object.assign({}, this.listQuery, { export: 1 })).then(response => {
          this.dlist = response.data.items
          const data = this.dlist.map(v => filterVal.map(j => {
            return v[j]
          }))
          // console.log(tHeader)
          // console.log(data)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: '行为日志'
          })
          this.downloadLoading = false
        })
      })
    },
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        return v[j]
      }))
    },
    // 全选
    handleCheckAll(val, item) {
      // 过滤掉没有选中的数据，item.child中不包含v时返回-1
      const next = item.children.map(item => item.id)
      const filterArr = this.selectedData.filter(
        (v) => next.indexOf(v) === -1
      )
      this.selectedData = val ? filterArr.concat(next) : filterArr
    },
    itemIndeterminate(item) {
      const infoLists = item.children.map(ite => ite.id)
      return (
        infoLists.some((v) => this.selectedData.indexOf(v) > -1) &&
        !infoLists.every((v) => this.selectedData.indexOf(v) > -1)
      )
    },
    // 勾选变化方法
    handleChanges(val) {
      const infoLists = val.children.map(ite => ite.id)
      infoLists.every((v) => {
        if (this.selectedData.indexOf(v) > -1) {
          val.flag = true
        } else {
          val.flag = false
        }
      })
    },
    selectTypeClick() {
      this.dialogVisible = true
    },
    confirmSubmit() {
      this.dialogVisible = false
      this.selectType = '已选择'
    },
    handleFilter() {
      this.getList(default_pages)
    }
  }
}
</script>
